package DAO.RequeteDAO;

import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import DAO.DAO_Bd;
import Metier.Table;
import Metier.Requete.ResultatRequete;

public abstract class RequeteDAO_Bd implements RequeteDAO {
	protected DAO_Bd dao;

	public List<Table> getListeTable() throws SQLException {
		List<Table> list = new ArrayList<Table>();

		DatabaseMetaData md = dao.getCx().getMetaData();
		String[] tab = new String[1];
		tab[0] = "TABLE";
		ResultSet rs = md.getTables(null, md.getUserName(), "%", tab);
		while (rs.next()) 
		{
			if (rs.getString(3).indexOf("==$0")==-1)
			{
				list.add(new Table(rs.getString(3),true));
			}
		}
		rs.close();
		return list;
	}

	public ResultatRequete executer(String select,String from,String join,String where)throws SQLException
	{
		String requete = "SELECT ";
		requete+=select;
		requete+="\n FROM ";
		requete+=from;
		requete+="\n ";
		if(join!=null)
		requete+=join;
		requete+="\n ";
		if (!where.equals(""))
		{
			requete+="\n WHERE ";
			requete+=where;
		}
		System.out.println(requete);
		ResultSet rs = dao.getSt().executeQuery(requete);
		ResultatRequete rr = new ResultatRequete();
		rr.init();
		rr.setRequete(requete);
		boolean debut = false;
		while (rs.next())
		{
			rr.nextTuple();
			try{

				ResultSetMetaData rsm = rs.getMetaData();
				int nbCol = rsm.getColumnCount();
				if (!debut)
				{
					for(int i=0;i<nbCol;i++)
					{
						rr.addTitreColonne(rsm.getColumnName(i+1));
					}
					debut = true;
				}

				for(int i=0;i<nbCol;i++)
				{
					rr.nextValeur(rs.getObject(i+1));
				}
			}
			catch(Exception e)
			{e.printStackTrace();}
		}
		rs.close();
		return rr;
	}
}